/**
 * @description jwt的token验证中间件
 * @author 盘挂他爹
 */

import { JwtVerify } from "../utils/jwt"
import ResponseModel from "../config/response.config"
import { userDoNotLogin } from "../config/errorInfo"
import { ICtxUser } from "../types"
import { Context } from "vm"
import * as Koa from "koa"
import * as WebSocket from "ws"
export async function JwtAuth(ctx: Context, next: any) {
  // console.log(ctx.request.header);

  let token = ctx.request.header.authorization
  // console.log(ctx.request.body);
  if (!token) {
    ctx.body = ResponseModel.error(userDoNotLogin)
    console.log("没有token", ctx.request.header);

    return
  }
  token = token.replace("Bearer ", "")
  // console.log("拿到的token", token);

  try {

    var res: ICtxUser = JwtVerify(token)
    ctx.userInfo = res
    console.log("token验证结果", ctx);
    // ctx.userInfo as ICtxUser

    await next()
  } catch (err) {
    // err
    console.log(err);

  }
}

export function JwtWebSocket(token: string) {
  // console.log(ctx.request.body);
  let res: any = false
  // console.log("token11:", token);

  if (token) {
    token = token.replace("Bearer ", "")
    try {
      // console.log("有token", token);
      var result = JwtVerify(token)
      // ctx.userInfo as ICtxUser
      if (result) {
        res = result
        return res
      }
    } catch (err) {
      console.error(err);
      return res
    }
  }

  return res

}